package com.itany.action;

import com.itany.jdbc.factory.ObjectFactory;
import com.itany.pojo.Dept;
import com.itany.service.DeptService;
import com.itany.service.proxy.ProxyTransaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年11月23日 11:29
 * @Description TODO
 */
@WebServlet("/action/dept/*")
public class DeptAction extends HttpServlet {

    private DeptService ds = ObjectFactory.getObj("DeptService");
    private DeptService dsProxy = ObjectFactory.getProxy("DeptService",new ProxyTransaction(ds));


//    @Override
//    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        String method = req.getMethod();
//        switch (method){
//            case "GET" : doGet(req,res); break;
//        }
//    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        通过session判断用户是否登录
//        HttpSession session = req.getSession();
//        if(session.getAttribute("user")==null){
//            resp.sendRedirect(req.getContextPath()+"/login.jsp");
//        }else{
//            String pathInfo = req.getPathInfo();
//            switch (pathInfo){
//                case "/all" :
//                    findAllDetp(req,resp);
//                    break;
//                case "/get" :
//                    findDetpDetail(req,resp);
//            }
//        }
        String pathInfo = req.getPathInfo();
        switch (pathInfo){
            case "/all" :
                findAllDetp(req,resp);
                break;
            case "/get" :
                findDetpDetail(req,resp);
        }
    }

    private void findDetpDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String deptno = req.getParameter("deptno");
        Dept detpDetail = dsProxy.findDetpDetail(deptno);
        req.setAttribute("dept",detpDetail);
        req.setAttribute("path","deptDetail.jsp");
        req.getRequestDispatcher("/WEB-INF/home.jsp").forward(req,resp);
    }

    private void findAllDetp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Dept> depts = dsProxy.findAllDetp();
        req.setAttribute("depts",depts);
//        req.getRequestDispatcher("/WEB-INF/template/dept.jsp").forward(req,resp);
        req.setAttribute("path","dept.jsp");
        req.getRequestDispatcher("/WEB-INF/home.jsp").forward(req,resp);
    }
}










